package luj.tool.jnproxyan.proxy.network.socksv2.server.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import luj.tool.jnproxyan.framework.lujnet.ConnState;
import luj.tool.jnproxyan.proxy.network.logger.Client2pLogger;
import luj.tool.jnproxyan.proxy.network.socksv2.connection.ConnStateAttr;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class C2pLogHandler extends ChannelDuplexHandler {

  @Override
  public void channelActive(ChannelHandlerContext ctx) {
    ConnState c2pConn = new ConnStateAttr(ctx.channel()).get();
    new Client2pLogger(LOG, c2pConn.getReqId()).log("与<浏>连上{-{-{-{-{-{-{-{-{-{-{-{-");

    ctx.fireChannelActive();
  }

  @Override
  public void channelInactive(ChannelHandlerContext ctx) {
    ConnState c2pConn = new ConnStateAttr(ctx.channel()).get();
    new Client2pLogger(LOG, c2pConn.getReqId()).log("与<浏>断开-}-}-}-}-}-}-}-}-}-}-}-}");

    ctx.fireChannelInactive();
  }

  @Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) {
    ConnState c2pConn = new ConnStateAttr(ctx.channel()).get();

    var data = (ByteBuf) msg;
    new Client2pLogger(LOG, c2pConn.getReqId()).log("收到<浏>B，大小：{}", data.readableBytes());

    ctx.fireChannelRead(msg);
  }

  @Override
  public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    ConnState c2pConn = new ConnStateAttr(ctx.channel()).get();

    var data = (ByteBuf) msg;
    new Client2pLogger(LOG, c2pConn.getReqId()).log2c("发送B给<浏>，大小：{}", data.readableBytes());

    ctx.write(msg, promise);
  }

  private static final Logger LOG = LoggerFactory.getLogger(C2pLogHandler.class);
}
